package com.ljw.gulimall.order.interceptor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ljw.common.utils.GetCookieUtils;
import com.ljw.common.utils.JwtUtils;
import com.ljw.gulimall.order.vo.MemberVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberVo> loginUser = new ThreadLocal<>();

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 拦截订单的所有的请求，检查用户是否登入
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match1 = antPathMatcher.match("/order/order/status/**", requestURI);
        boolean match2 = antPathMatcher.match("/payed/notify", requestURI);
        if (match1 || match2){
            return true;
        }
        //获取cookie中用户的id
        String memberId = GetCookieUtils.getMemberIdFormCookie(request);
        //如果用户的id为空则说明用户没有登入
        if (!StringUtils.isEmpty(memberId)){
            String memberJson = redisTemplate.opsForValue().get(memberId);
            if (!StringUtils.isEmpty(memberJson)){
                MemberVo memberVo = JSONObject.parseObject(memberJson, MemberVo.class);
                loginUser.set(memberVo);
                return true;
            }
        }
        //没登入，无法进入订单系统，跳转到登入界面
        response.sendRedirect("http://auth.gulimall.com/login.html");
        return false;
    }
}
